//
//  WmcCloudAlbumBaseTabBarVC.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import UIKit
import YPBedrock

// MARK: - [WmcCloudAlbumBaseTabBarVC]

open class WmcCloudAlbumBaseTabBarVC: WmcBaseTabBarVC {
    // Lifecycle

    open override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        slideBarAnimation = .init(tabbarVC: self)
    }

    // Open

    open override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        // 点击动画
        tabBarButtonClick(tabBarButton: getTabBarButton(item.tag))
    }

    /// 添加子控制器
    open func addCloudAlbumChildVC(_ childVC: UIViewController,
                                   childTitle: String,
                                   normalImage: UIImage,
                                   selectedImage: UIImage) {
        addChildVC(childVC, childTitle: childTitle, normalImage: normalImage, selectedImage: selectedImage) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.rootPopVC()
        }
    }

    // Internal

    /// 滑动动画
    var slideBarAnimation: WmcCloudAlbumBaseTabBarVC.SlideBarAnimation?

    /// 根视图返回
    var rootPopVCBlock: YPBlock.Empty?

    /// 双重导航条，直接转移事件
    func rootPopVC() {
        if let rootPopVCBlock = rootPopVCBlock {
            rootPopVCBlock()
        } else {
            navigationController?.popViewController(animated: true)
        }
    }
}

// MARK: UITabBarControllerDelegate

extension WmcCloudAlbumBaseTabBarVC: UITabBarControllerDelegate {
    /// 滑动动画
    public func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return slideBarAnimation // 滑动动画
    }
}

// MARK: WmcCloudAlbumBaseTabBarVC.SlideBarAnimation

extension WmcCloudAlbumBaseTabBarVC {
    class SlideBarAnimation: NSObject {
        // Lifecycle

        init(tabbarVC: UITabBarController) {
            self.tabbarVC = tabbarVC
        }

        // Internal

        weak var tabbarVC: UITabBarController?
    }
}

// MARK: - WmcCloudAlbumBaseTabBarVC.SlideBarAnimation + UIViewControllerAnimatedTransitioning

extension WmcCloudAlbumBaseTabBarVC.SlideBarAnimation: UIViewControllerAnimatedTransitioning {
    /// 设置时间间隔
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.15
    }

    /// 处理转场
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromeVC = transitionContext.viewController(forKey: .from),
              let toVC = transitionContext.viewController(forKey: .to),
              let tabbarVC = tabbarVC,
              let fromeIndex = tabbarVC.viewControllers?.firstIndex(where: { $0 == fromeVC }),
              let toIndex = tabbarVC.viewControllers?.firstIndex(where: { $0 == toVC }),
              let formView = transitionContext.view(forKey: .from),
              let toView = transitionContext.view(forKey: .to) else {
            return transitionContext.completeTransition(true)
        }

        let fromFrame: CGRect = formView.frame
        let toFrame: CGRect = toView.frame

        var offSet: CGVector? // 偏移矢量
        if toIndex > fromeIndex {
            offSet = CGVector(dx: -1, dy: 0)
        } else {
            offSet = CGVector(dx: 1, dy: 0)
        }

        guard let animOffSet = offSet else {
            return transitionContext.completeTransition(true)
        }
        formView.frame = fromFrame

        let ofDx: CGFloat = animOffSet.dx
        let ofDy: CGFloat = animOffSet.dy
        toView.frame = CGRect.offsetBy(toFrame)(dx: toFrame.size.width * ofDx * -1, dy: toFrame.size.height * ofDy * -1)
        transitionContext.containerView.addSubview(toView)

        UIView.animate(withDuration: Wmc_animationDuration,
                       delay: 0,
                       options: .curveEaseInOut) {
            formView.frame = CGRect.offsetBy(fromFrame)(dx: fromFrame.size.width * ofDx * 1, dy: fromFrame.size.height * ofDy * 1)
            toView.frame = toFrame
        } completion: { _ in
            transitionContext.completeTransition(true)
        }
    }
}

fileprivate extension WmcCloudAlbumBaseTabBarVC {
    // Private

    func getTabBarButton(_ index: Int) -> UIControl? {
        var tabBarButtons = [UIView]()
        for tabBarButton in tabBar.subviews {
            if (tabBarButton.isKind(of: NSClassFromString("UITabBarButton")!)) {
                tabBarButtons.append(tabBarButton)
            }
        }
        return tabBarButtons[index] as? UIControl
    }

    func tabBarButtonClick(tabBarButton: UIControl?) {
        guard let tabBarButton = tabBarButton else { return }
        tabBarButton.yp.makeAnimation { make in
            make.keyframeAnimation(.transform_scale) { make in
                make.set(duration: 0.3)
                    .set(calculationMode: .cubicPaced)
                    .set(values: [1.0, 1.2, 0.8, 1.1, 0.9, 1.0])
            }
        }
    }
}
